#include "applicationinfo.h"
#include "appchat/profilemanager.h"

#include <QtGui/QGuiApplication>
#include <QtGui/QScreen>
#include <QDateTime>
#include <QDebug>
#include <QMessageBox>
#include <QDir>
#include <QSortFilterProxyModel>;


ApplicationInfo::ApplicationInfo(QObject *parent) :
    QObject(parent)
{
    m_isMobile = false;
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS) || defined(Q_OS_BLACKBERRY)
    m_isMobile = true;
#endif

    qDebug()<< " @@@ ApplicationInfo is mobile " << m_isMobile ;
    m_colors = new QQmlPropertyMap(this);
    m_colors->insert(QLatin1String("white"), QVariant("#ffffff"));
    m_colors->insert(QLatin1String("smokeGray"), QVariant("#eeeeee"));
    m_colors->insert(QLatin1String("paleGray"), QVariant("#d7d6d5"));
    m_colors->insert(QLatin1String("lightGray"), QVariant("#aeadac"));
    m_colors->insert(QLatin1String("darkGray"), QVariant("#35322f"));
    m_colors->insert(QLatin1String("mediumGray"), QVariant("#5d5b59"));
    m_colors->insert(QLatin1String("doubleDarkGray"), QVariant("#1e1b18"));
    m_colors->insert(QLatin1String("blue"), QVariant("#14aaff"));
    m_colors->insert(QLatin1String("darkBlue"), QVariant("#14148c"));

    m_constants = new QQmlPropertyMap(this);
    m_constants->insert(QLatin1String("isMobile"), QVariant(m_isMobile));
    m_constants->insert(QLatin1String("errorLoadingImage"), QVariant(tr("Error loading image - Host not found or unreachable")));


    QRect rect = qApp->primaryScreen()->geometry();
    qDebug()<< " @@@ ApplicationInfo is mobile " << rect.width() << " "<< rect.height();
    m_ratio = m_isMobile ? qMin(qMax(rect.width(), rect.height())/800. , qMin(rect.width(), rect.height())/480.) : 1;
    m_applicationWidth = m_isMobile ? rect.width() : 1120;

    m_activeUid = -1;
    m_isLogin = false;
    m_friendListModel = new FriendListModel();
    m_friendSearchModel = new FriendListModel();
    m_friendListSortByNameModel = new FriendListModel();
    m_friendListOnlineModel = new FriendListModel();


    initChatManager();
}

void ApplicationInfo::notifyPortraitMode()
{
    int width = qApp->primaryScreen()->geometry().width();
    int height = qApp->primaryScreen()->geometry().height();
    setIsPortraitMode(height > width);
}

void ApplicationInfo::setIsPortraitMode(const bool newMode)
{
    if (m_isPortraitMode != newMode) {
        m_isPortraitMode = newMode;
        emit portraitModeChanged();
    }
}


void ApplicationInfo::setApplicationWidth(const int newWidth)
{
    if (newWidth != m_applicationWidth) {
        m_applicationWidth = newWidth;
        emit applicationWidthChanged();
    }
}

void ApplicationInfo::initChatManager()
{
    qDebug() << " initChatManager ";
    ChatManager::instance();

    chatManager = ChatManager::instance();

    connect (chatManager,
             &ChatManager::logined,
             this,
             &ApplicationInfo::onLogined);

    connect(chatManager,
            &ChatManager::logouted,
            this,
            &ApplicationInfo::onLogouted);

    connect (ProfileManager::instance(),
             &ProfileManager::getAllFriendProfileFinish,
             this,
             &ApplicationInfo::onGetAllProfileFinish);

    connect (ProfileManager::instance(),
             &ProfileManager::startGetListFriendSortByName,
             this,
             &ApplicationInfo::onGetListFriendsSortByName);

    connect (ProfileManager::instance(),
             &ProfileManager::startGetListFriendSortByNameFirstTime,
             this,
             &ApplicationInfo::onGetListFriendsSortByNameFirstTime);


    connect (ProfileManager::instance(),
             &ProfileManager::refreshCurrentListFriendSuccessfull,
             this,
             &ApplicationInfo::onRefreshCurrentListFriend);

    connect (ProfileManager::instance(),
             &ProfileManager::getUnitFriendsProfile,
             this,
             &ApplicationInfo::onGetUnitFriendsProfile);

    connect (ProfileManager::instance(),
             &ProfileManager::getAllFriendsOnline,
             this,
             &ApplicationInfo::onGetAllFriendsOnline);

    connect (ProfileManager::instance(),
             &ProfileManager::createNewGroupSucessfull,
             this,
             &ApplicationInfo::onCreateNewGroupSucessfull);



    connect (chatManager,
             &ChatManager::requestBuddiesFinished,
             this,
             &ApplicationInfo::onRequestBuddiesFinished);

    connect (chatManager,
             &ChatManager::messageReadFromLocal,
             this,
             &ApplicationInfo::onMessageReadFromLocal);

    connect (chatManager,
             &ChatManager::messageSend,
             this,
             &ApplicationInfo::onMessageSend);

    connect (chatManager,
             &ChatManager::messageSent,
             this,
             &ApplicationInfo::onMessageSent);

    connect (chatManager,
             &ChatManager::messageReceived,
             this,
             &ApplicationInfo::onMessageReceived);

    connect(AccountManager::instance(),
            &AccountManager::requireLogin,
            this,
            &ApplicationInfo::onRequireLogin);

    connect (AccountManager::instance(),
             &AccountManager::notifyError,
             this,
             &ApplicationInfo::onNotifyError);

    connect (AccountManager::instance(),
             &AccountManager::activedCode,
             this,
             &ApplicationInfo::onActiveCore);

}
void ApplicationInfo::onLogined(bool successed, qint64 uid)
{
    if (successed == false)
        return;
    emit loginSuccess();

    m_activeUid = chatManager->activeUid();
    emit activeUidChanged();

    m_fullName = AccountManager::instance()->getUserProfile()->getDisplayName();

    //QString str = QDir::currentPath();
    //str.append("/MeQml/Avatar/");
    m_avatarUser = AccountManager::instance()->getUserProfile()->getAvatar();


    //emit startOpeningFriendListPage();
}

void ApplicationInfo::onLogouted()
{
    emit logoutAccountSuccess();
    qDebug()<< "================================== ApplicationInfo::onLogouted ";
}

void ApplicationInfo::onMessageSend(Converse::AbstractMessage *message)
{
    // hien thi message gui tam thoi len form
    qint64 fid = message->receiverId();

    ConversationModel* aConversationModel = getConversationModel(fid);
    if (aConversationModel == NULL)
        return;

    aConversationModel->insertConversation(0, message);
}

void ApplicationInfo::onMessageSent(Converse::AbstractMessage *message)
{
    // xu ly thong bao da gui message thanh cong
    qint64 fid = message->receiverId();

    ConversationModel* aConversationModel = getConversationModel(fid);
    if (aConversationModel == NULL)
        return;

    aConversationModel->editConversation(message);
}

void ApplicationInfo::onMessageReceived(Converse::AbstractMessage *message)
{

    qint64 uid = AccountManager::instance()->getUserId();
    qint64 fid;
    if (uid == message->senderId()) {
        fid = message->receiverId();
    } else {
        fid = message->senderId();
    }
    qDebug() << "void ApplicationInfo::onMessageReceived : senderId" << fid;

    ConversationModel* aConversationModel = getConversationModel(fid);
    if (aConversationModel == NULL) {
        aConversationModel = new ConversationModel(this);
        insertConversationModel(fid, aConversationModel);

        chatManager->getHistoryMessageFromLocal(uid, fid);
    }

    aConversationModel->insertConversation(0, message);

    emit positionViewAtIndexMessage();
}

void ApplicationInfo::onMessageReadFromLocal(Converse::AbstractMessage *message)
{
    qint64 senderId = message->senderId();
    qint64 receiverId = message->receiverId();
    qint64 fid;

    if (AccountManager::instance()->getUserId() == senderId) {
        fid = receiverId;
    } else {
        fid = senderId;
    }


    ConversationModel* aConversationModel = getConversationModel(fid);
    if (aConversationModel == NULL)
        return;

    aConversationModel->insertConversation(0, message);

}


void ApplicationInfo::onRequestBuddiesFinished()
{
    // se sort lai danh sach hien thi cua friends list tai day va hien thi lai
}



void ApplicationInfo::onHasDpiScreen(QString dpi)
{
    if (dpi == "ldpi") {
        m_dpi = "mdpi";
    } else {
        m_dpi = dpi;
    }

    emit dpiChanged();
}

void ApplicationInfo::onDologin(QString username, QString password)
{
    chatManager->doLogin(username, password);

}
void ApplicationInfo::onDoLogout()
{
    chatManager->doLogout();

    m_friendListModel->clear();
    m_friendSearchModel->clear();
    m_friendListSortByNameModel->clear();
    m_friendListOnlineModel->clear();

    if (m_mapConversationModel.size() == 0)
        return;

    int CountConversation = m_mapConversationModel.size();
    for (int i = 0; i < CountConversation; i++) {
        qint64 fisrtKey = m_mapConversationModel.firstKey();

        ConversationModel* aConversationModel = m_mapConversationModel.first();

        aConversationModel->clear();
        delete aConversationModel;

        m_mapConversationModel.remove(fisrtKey);
    }

    //qDeleteAll(m_mapConversationModel);
    m_mapConversationModel.clear();
}

void ApplicationInfo::onDoSearchFriends(QString txtInput)
{
    qDebug() << "ApplicationInfo::onDoSearchFriends : " << txtInput;
    txtInput.trimmed();
    m_friendSearchModel->clear();

    QList<UserProfile*> listSearchFriends  = ProfileManager::instance()->getSearchFriends(txtInput);

    m_friendSearchModel->setListBuddy(listSearchFriends);

    qDebug() <<"[[[[[[[[[[[[[[[[[[[[[[[[" << listSearchFriends.length();

    emit friendSearchModel();
}

void ApplicationInfo::onGetActiveCodeRequest(QString phone)
{
    qDebug() << "ApplicationInfo::onGetActiveCodeRequest" + phone;
    chatManager->doGetActiveCode(phone);
}

void ApplicationInfo::onMakeAcountRequest(QString phone, QString activeCode)
{
    qDebug() << "ApplicationInfo::onMakeAcountRequest  phone : "+ phone + " activeCode :" + activeCode;
    chatManager->doCreateNewAccount(phone, activeCode);
}

void ApplicationInfo::onUpdateContactData(qint64 buddyId, qint64 uid, int totalMember)
{
    Q_UNUSED(uid);

    if (totalMember == 1) {
        chatManager->updatePrivateContactData(buddyId);
    } else if (totalMember >1) {
        chatManager->updateGroupContactData(buddyId);
    } else {
        return;// thoat
    }

    FriendListModel* aFriendListModel = friendListModel();
    if (aFriendListModel == NULL)
        return;

    ConversationModel* aConversationModel = getConversationModel(buddyId);

    if (aConversationModel == NULL) {
        aConversationModel = new ConversationModel(this);
        insertConversationModel(buddyId, aConversationModel);

        chatManager->getHistoryMessageFromLocal(uid, buddyId);
    }
}

void ApplicationInfo::onSendMessage(QString message)
{
    chatManager->sendMessage(message);
}

void ApplicationInfo::initData()
{
    QString sessionKey = AccountManager::instance()->getSessionKey();
    qDebug()<< "sssionKey get " << sessionKey;

    if(sessionKey == ""){
        emit requireLogin();
    }else{
        AccountManager::instance()->postRequestGetProfile();
    }
}

void ApplicationInfo::onGetUnitFriendsProfile(QList<UserProfile *> aUnitFriends)
{
    // goi hien thi page list friend 1 lan
    if (m_friendListModel->listBuddyItems().length() == 0)
        emit startOpeningFriendListPage();

    m_friendListModel->insertUnitBuddy(aUnitFriends);

}

void ApplicationInfo::onGetAllFriendsOnline(QList<UserProfile*> listFriendsOnline)
{
    m_friendListOnlineModel->setListBuddy(listFriendsOnline);

    m_friendListModel->setListBuddy(ProfileManager::instance()->getListFriendProfile());
}

void ApplicationInfo::onGetListFriendsSortByName()
{
    m_friendListSortByNameModel->setListBuddy(ProfileManager::instance()->getListFriendsProfileSortByName());
}

void ApplicationInfo::onGetListFriendsSortByNameFirstTime()
{
    m_friendListSortByNameModel->setListBuddy(ProfileManager::instance()->getListFriendsProfileSortByNameFirtTime());
}

void ApplicationInfo::onGetAllProfileFinish()
{
    qDebug() << "ApplicationInfo::onGetAllProfileFinish()";
    m_friendListModel->setListBuddy(ProfileManager::instance()->getListFriendProfile());
    emit startOpeningFriendListPage();
}

void ApplicationInfo::onRefreshCurrentListFriend()
{
    m_friendListModel->setListBuddy(ProfileManager::instance()->getListFriendProfile());

}

void ApplicationInfo::setIsLogin(const bool isLogin){
    m_isLogin = isLogin;
    emit isLoginChanged();
}


void ApplicationInfo::onRequireLogin()
{
    emit requireLogin();
}

void ApplicationInfo::onNotifyError(int type)
{
    if (type == 1) {
        emit notifyActiveCode(-1); // ko co mang
    }
}


void ApplicationInfo::onActiveCore(int successed)
{
    emit notifyActiveCode(successed);
}

void ApplicationInfo::onAddFriendToGroup(qint64 uid, qint64 fid, QString displayName)
{
    qDebug() <<"ApplicationInfo::onAddFriendToGroup" << uid<< fid<<displayName;

    Q_UNUSED(displayName);
    ProfileManager::instance()->addFriendToGroup(uid, fid);
}

void ApplicationInfo::onDeleteFriendFromGroup(qint64 uid, qint64 fid, QString displayName)
{
    qDebug() <<"ApplicationInfo::onDeleteFriendFromGroup" << uid<< fid<<displayName;
    Q_UNUSED(displayName);
    ProfileManager::instance()->deleteFriendFromGroup(uid, fid);
}
void ApplicationInfo::onCreateGroup(QString groupName)
{
    qDebug() <<"ApplicationInfo::onCreateGroup()";
    ProfileManager::instance()->doCreateGroup(groupName);
}

void ApplicationInfo::onCreateNewGroupSucessfull()
{
    m_friendListModel->setListBuddy(ProfileManager::instance()->getListFriendProfile());
}
